<template>
  <el-form size="small" :model="searchForm" label-width="0px" class="m-t-10 form-live-weather">
    <el-form-item class="select-date">
      <div class="flex-block btn-control">
      <el-button class="btn-left" icon="el-icon-arrow-left" @click="handleDate('prev')"></el-button>
      <el-date-picker
        v-model="searchForm.dt"
        type="datetime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期"
        popper-class="drawer-date-range"
        :default-time="defaultTime"
        @change="getList"
        :picker-options="pickerDate">
      </el-date-picker>
      <el-button class="btn-right" icon="el-icon-arrow-right" :disabled="btnDisabled.next" @click="handleDate('next')"></el-button>
    </div>
    </el-form-item>
    <el-form-item>
      <el-radio-group v-model="searchForm.type" @change="changeType">
        <el-radio-button v-for="(item,index) in initData.types" :key="index" :label="item.value">{{ item.label }}</el-radio-button>
      </el-radio-group>
      <!-- <el-button v-for="(item,index) in initData.types" :key="index" size="small" :type="searchForm.type == item.value ? 'primary' : 'default'" @click="changeType(item.value)">
        {{ item.label }}
      </el-button> -->
    </el-form-item>
  </el-form>
</template>
<script>
import {types,legendColors,typesRenderer,popupTemplate} from '@/views/page/live-weather/config';
import {city,cityPinyin} from '@/config/env'
import * as mapboxgl from 'mapbox-gl';
export default {
  data(){
    return {
      searchForm:{
        dt: '',
        type: 'wind_speed',
      },
      defaultTime: '',
      btnDisabled:{
        prev: false,
        next: false,
      },
      initData:{
        startTime: 0,
        endTime: 23,
        fpDate: [],
        types: types,
        legend: legendColors,
      },
      selectType:{
        active: ['1'],
        name: '',
        unit: '',
        list: [],
        isLoad: false,
      },
      pickerDate:{
        disabledDate: (time)=>{
          const current = new Date(this.$moment().format('YYYY-MM-DD')).getTime();
          const start = new Date('2017-01-01').getTime();
          return time.getTime() > current || time.getTime() < start;
        }
      },
      list:[],
      selData: null,
      addedImages: [],
      legends: [],
    }
  },
  created() {
    let dt = this.$moment().format('YYYY-MM-DD');
    let hour = new Date().getHours() - 1;
    this.searchForm.dt = dt + ' ' + hour + ':00:00';
    this.defaultTime = this.$moment().format('HH')+':00:00';
  },
  watch:{
    'searchForm.dt'(newVal,oldVal){
      if(new Date(newVal).getTime() >= new Date(this.$moment().format('YYYY-MM-DD HH')+':00:00').getTime()){
        this.searchForm.dt = this.$moment().format('YYYY-MM-DD HH')+':00:00';
        this.btnDisabled.next = true;
      }else{
        this.btnDisabled.next = false;
      }
    }
  },
  methods:{
    getList(){
      this.map = this.$parent.map; 
      // this.changeType(this.searchForm.type);    
      this.$request('get', '/air/nmc/current', {dt: this.searchForm.dt}, (data,msg) => {
        this.list = data.filter(i => city.indexOf(i.city) > -1);
        this.addImages();
      })
    },
    changeType(val){
      this.searchForm.type = val;
      let res = this.initData.legend[val];
      let obj = this.initData.types.find(item => item.value == val);
      this.selectType.name = obj.label;
      this.selectType.unit = obj.unit;
      this.selectType.list = res.colors;
      // if(this.selectType.isLoad){
        this.addImages();
      // };
    },
    handleDate(type){
      let arr = this.searchForm.dt.split(' ');
      let d = arr[0];
      let arrTime = arr[1].split(':');
      let t = Number(arrTime[0]);
      let dt = '';
      if(type == 'prev'){
        if(t == 0 ){
          let lastD = this.$moment(d).add(-1, 'd').format('YYYY-MM-DD');
          dt = lastD + ' 23:00:00';
        }else{
          dt = d + ' ' + this.getTime(t-1) + ':00:00';
        }
      }else{
        if(t == 23){
          let nextD = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
          dt = nextD + ' 00:00:00';
        }else{
          dt = d + ' ' + this.getTime(t+1) + ':00:00';
        }
      }
      this.searchForm.dt = dt;
      this.getList();
    },
    getTime(val){
      return val < 10 ? ('0'+val) : val;
    },
    addImages(){
      const type = this.searchForm.type;
      if (!legendColors[type].isImage) {
        this.legends = legendColors[type].colors;
        this.addLayer();
        return;
      }
      const images = legendColors[type].icons;
      this.legends = images;
      images.forEach((img, index) => {
        this.map.loadImage(img.url, (error, image) => {
          if (error) throw error;
          if (!this.map.hasImage(img.id)){
            this.map.addImage(img.id, image);
          }
          this.addedImages.push(img.id);
          if (index === images.length - 1) {
            this.addLayer();
          }
        });
      })
    },
    addLayer(){
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      const type = this.searchForm.type;
      for(const d of this.list) {
        const item = d;
        if (Number(item[type]) !== null) {
          geojson.features.push({
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [d.lon, d.lat]
            },
            properties: d
          });
        }
      }
      if (this.map.getLayer('live-weather-label')) {
        this.map.removeLayer('live-weather-label');
      }
      if (this.map.getLayer('live-weather-layer')) {
        this.map.removeLayer('live-weather-layer');
      }
      this.map.resize();
      console.log(this.map.getStyle().layers);
      if (!this.map.getSource('live-weather-source')) {
        this.map.addSource('live-weather-source', {
          type: 'geojson',
          data: geojson
        });
      } else {
        (this.map.getSource('live-weather-source')).setData(geojson);
      }
      let newTypeR = JSON.parse(JSON.stringify(typesRenderer));
      if (!this.map.getLayer('live-weather-layer')) {
        newTypeR[type].layer.id = 'live-weather-layer';
        newTypeR[type].layer.source = 'live-weather-source',
        this.map.addLayer(newTypeR[type].layer, 'area-border');
      }
      if (type !== 'wind_speed'  && !this.map.getLayer('live-weather-label') ){
        newTypeR.label.layer.layout['text-field'][1] = type;
        newTypeR.label.layer.id = 'live-weather-label';
        newTypeR.label.layer.source = 'live-weather-source';
        newTypeR.label.layer.layout['text-font'] = ['Noto Sans Regular']
        this.map.addLayer(newTypeR.label.layer,'area-border');
      }
      this.map.resize();
      this.addPopup();
    },

    addPopup(){
      const popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false
      });
      this.map.on('mouseenter', 'live-weather-layer', (e) => {
        this.map.getCanvas().style.cursor = 'pointer';
        const coordinates = e.features[0].geometry.coordinates.slice();
        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
          coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
        }
        const prop = e.features[0].properties;
        let html = `<div class="map-popup-container">`;
        html += `<div class="popup-title">${prop.city}市${prop.station_name}站实况气象基本信息</div>`;
        html += '<div class="popup-content"><table class="popup-table">';
        popupTemplate.forEach(p => {
          if (p.dataType === 'dateTime') {
            html += `<tr><td>${p.label}</td><td>${prop[p.field] ? prop[p.field].replace('T', ' ') : '/'}</td></tr>`;
          } else if (p.field === 'wind_direction') {
            const val = prop[p.field];
            let direction = '';
            if (val <= 22.5) {
              direction = '北';
            } else if (val <= 67.5) {
              direction = '东北';
            } else if (val <= 112.5) {
              direction = '东';
            } else if (val <= 157.5) {
              direction = '东南';
            } else if (val <= 202.5) {
              direction = '南';
            } else if (val <= 247.5) {
              direction = '西南';
            } else if (val <= 292.5) {
              direction = '西';
            } else if (val <= 337.5) {
              direction = '西北';
            } else {
              direction = '北';
            }
            html += `<tr><td>${p.label}</td><td>${direction}</td></tr>`;
          } else if (p.unit) {
            html += `<tr><td>${p.label}</td><td>${prop[p.field]}${p.unit}</td></tr>`;
          } else {
            html += `<tr><td>${p.label}</td><td>${prop[p.field]}</td></tr>`;
          }
        })
        html += '</table></div>'
        html += '</div>';
        popup.setLngLat(coordinates)
          .setHTML(html)
          .addTo(this.map);
      });
      this.map.on('mouseleave', 'live-weather-layer', () => {
        this.map.getCanvas().style.cursor = '';
        popup.remove();
      });
    },
  }
}
</script>


